import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import './index.less'

class Dialog extends Component {
  constructor(props) {
    super(props)
  }
  render() {
    const { 
      title="提示", // 弹框标题
      message="", // 弹框内容
      okBtn="确定", // 确定按钮文案
      cancelBtn, // 取消按钮文案，不设置默认不显示
      closeCallback, // 点击右上角关闭按钮后的回调
      okCallback, // 点击确定后的回调
      cancelCallback, // 点击取消按钮的回调
    } = this.props
    return (
      <div className="dialog-container">
        <div className="dialog">
          <span onClick={closeCallback} className="d-close"></span>
          <p className="d-title">{title}</p>
          <p className="d-message">{message}</p>
          <div className="btn-wrap">
            <span onClick={okCallback}>{okBtn}</span>
            {
              cancelBtn && <span onClick={cancelCallback}>{cancelBtn}</span>
            }
          </div>
        </div>
      </div>
    )
  }
}

export default options => {
  const _dialog_ = document.getElementById('_dialog_')
  if(_dialog_) { document.body.removeChild(_dialog_) }
  let { 
    title="提示", 
    message="", 
    okBtn="确定",
    cancelBtn, 
    closeCallback, 
    okCallback, 
    cancelCallback,
  } = options || {}
  let dialog = document.createElement('div')
  dialog.setAttribute('id', '_dialog_')
  document.body.appendChild(dialog)
  ReactDOM.render(React.createElement(Dialog, {
    title,
    message,
    okBtn,
    cancelBtn,
    closeCallback: () => {
      closeCallback && closeCallback()
      document.body.removeChild(dialog)
    },
    okCallback: () => {
      okCallback && okCallback()
      document.body.removeChild(dialog)
    },
    cancelCallback: () => {
      cancelCallback && cancelCallback()
      document.body.removeChild(dialog)
    }
  }), dialog)
}